package com.github.dengmin.mysql.common;

import com.github.dengmin.mysql.model.DatabaseConnection;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author dengmin
 * @Created 2020/6/29 下午7:55
 */
public class ConnectionPool {
    private static final long serialVersionUID = 1L;

    public static Map<Integer, HikariDataSource> pool = new ConcurrentHashMap<>();

    public synchronized static DataSource create(DatabaseConnection connection) {
        HikariDataSource dataSource = pool.get(connection.getId());
        if (dataSource == null) {
            dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(getMySQLDsn(connection.getHost(),connection.getDbName()));
            dataSource.setUsername(connection.getUsername());// 用户名
            dataSource.setPassword(connection.getPassword());// 密码
            dataSource.setMaximumPoolSize(10);
            pool.put(connection.getId(), dataSource);
        }
        return dataSource;
    }

    private static String getMySQLDsn(String host, String database){
        String dsn = "jdbc:mysql://%s:3306/%s?useSSL=false&useUnicode=false&autoReconnect=true&characterEncoding=utf-8&tcpRcvBuf=2048000&zeroDateTimeBehavior=convertToNull";
        return String.format(dsn, host, database);
    }


}
